package com.fmy.jurisdiction.config.spring.web;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import com.fmy.jurisdiction.core.commons.kits.RequestKit;
import com.fmy.jurisdiction.core.unusual.BizException;
import com.fmy.jurisdiction.core.web.call.ResponseCall;
import com.fmy.jurisdiction.core.web.specs.Response;
import com.fmy.jurisdiction.core.web.specs.ResponseEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName ExceptionalHandel
 * @Description TODO web全局异常处理
 * @createTime 2019/9/16 14:03
 */
@ControllerAdvice
@Slf4j
public class ExceptionalHandel {

    @ExceptionHandler(BizException.class)
    @ResponseBody
    public Response bizException(BizException e) {
        return ResponseCall.error(e.getIEnum(), e.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Response exception(Exception e) {
        log(e);
        return ResponseCall.error(ResponseEnum.SERVER_ERROR, ResponseEnum.SERVER_ERROR.getDesc());
    }

    private void log(Exception e) {
        HttpServletRequest request = RequestKit.getRequest();
        StringBuffer sb = new StringBuffer();
        Map<String, String[]> map = request.getParameterMap();
        if (map != null) {
            map.forEach((k, v) -> {
                sb.append(StrUtil.format("{}：{}", k, v));
            });
        }
        log.error(StrUtil.format("请求地址：{}、请求参数：{}、异常：{}", request.getRequestURI(), StrUtil.isBlank(sb) ? "无" : sb.toString(), ExceptionUtil.stacktraceToString(e)));
    }
}
